package com.lanchewuyou.user.driver.lipeiui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.lanchewuyou.user.driver.R;
import com.lanchewuyou.user.driver.adapter.OrderYesAdapter;
import com.lanchewuyou.user.driver.bean.OrderYesItem;
import com.lanchewuyou.user.driver.modul.Config;
import com.lanchewuyou.user.driver.modul.OkHttpClientManager;
import com.squareup.okhttp.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 往日订单列表fragment
 */
public class LipeiMainFragment2 extends android.support.v4.app.Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private ListView frgListview2;
    private SwipeRefreshLayout frgRefresh2;
    private List<OrderYesItem> orderYesItemList;
    private ImageView imageView;
    private String url;
    private OrderYesAdapter orderYesAdapter;
    private int page = 2;
    private Toast toast = null;

    private void showTextToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    public LipeiMainFragment2() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.lipei_main_fragment2, container, false);
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
        final String driverId = sharedPreferences.getString("driverid", "");
        frgListview2 = (ListView) v.findViewById(R.id.frg2_listview);
        frgRefresh2 = (SwipeRefreshLayout) v.findViewById(R.id.frg2_refresh);
        frgRefresh2.setColorScheme(R.color.mainred);
        frgRefresh2.setOnRefreshListener(this);
        imageView = (ImageView) v.findViewById(R.id.frg2_under);
        orderYesItemList = new ArrayList<>();
        orderYesAdapter = new OrderYesAdapter(orderYesItemList, getActivity());
        frgListview2.setAdapter(orderYesAdapter);
        url = Config.DRIVERORDERFINISH + "&page=1&num=10&driverid=" + driverId;
        frgListview2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OrderYesItem yseItem = orderYesItemList.get(position);
                String yesType = yseItem.getType();
                if (yesType.equals("送车订单")) {
                    Intent intent = new Intent(getActivity(), CaseInfoActivity.class);
                    intent.putExtra("caseid", yseItem.getId());
                    startActivity(intent);
                } else if (yesType.equals("还车订单")) {
                    Intent intent = new Intent(getActivity(), CaseReturnActivity.class);
                    intent.putExtra("caseid", yseItem.getId());
                    startActivity(intent);
                }
            }
        });
        frgListview2.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        frgRefresh2.setRefreshing(true);
                        OkHttpClientManager.getAsyn(Config.DRIVERORDERFINISH + "&page=" + page + "&num=10&driverid=" + driverId, new OkHttpClientManager.StringCallback() {
                            @Override
                            public void onFailure(Request request, IOException e) {
                                showTextToast("服务器出了点问题");
                                handler.sendEmptyMessageDelayed(0, 100);
                            }

                            @Override
                            public void onResponse(String response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String status = jsonObject.getString("status");
                                    if (status.equals("1")) {
                                        JSONObject orders = jsonObject.getJSONObject("orders");
                                        int count = orders.getInt("count");
                                        if (count == 0) {
                                            frgRefresh2.setRefreshing(false);
                                            showTextToast("没有新的订单");
                                        } else {
                                            JSONArray jsonArray = orders.getJSONArray("lists");
                                            for (int i = 0; i < jsonArray.length(); i++) {
                                                JSONObject item = (JSONObject) jsonArray.get(i);
                                                OrderYesItem orderYesItem = new OrderYesItem();
                                                String id = item.getString("id");
                                                orderYesItem.setId(id);
                                                String type = item.getString("huanche");
                                                //如果是0，则为送车订单
                                                if (type.equals("0")) {
                                                    orderYesItem.setAddress(item.getString("address"));
                                                    orderYesItem.setType("送车订单");
                                                    orderYesItem.setTime(item.getString("jieche_time"));
                                                    orderYesItem.setPhoto(item.getJSONObject("carimg").getJSONObject("lists").getJSONObject("7").getInt("count"));
                                                } else if (type.equals("1")) {
                                                    orderYesItem.setAddress(item.getString("huanche_address"));
                                                    orderYesItem.setType("还车订单");
                                                    orderYesItem.setTime(item.getString("expect_huanchetime"));
                                                    orderYesItem.setPhoto(item.getJSONObject("carimg").getJSONObject("lists").getJSONObject("8").getInt("count"));
                                                }
                                                String payType = item.getString("paid");
                                                if (payType.equals("0")) {
                                                    orderYesItem.setPayType("线下收费");
                                                } else if (payType.equals("1")) {
                                                    orderYesItem.setPayType("已收费");
                                                }
                                                orderYesItemList.add(orderYesItem);
                                            }
                                            // orderYesAdapter.notifyDataSetChanged();
                                            handler.sendEmptyMessageDelayed(0, 100);
                                            page = page + 1;
                                        }
                                    } else {
                                        handler.sendEmptyMessageDelayed(0, 100);
                                        showTextToast("没有新的订单");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    showTextToast("服务器出了点问题");
                                }
                            }
                        });
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
        return v;
    }

    @Override
    public void onRefresh() {
        updateData();
    }

    @Override
    public void onResume() {
        super.onResume();
        swipeRefresh(true);
        updateData();
    }

    /**
     * swiperefresh在主线程中无法消失，需要新开线程
     *
     * @param refresh
     */
    private void swipeRefresh(final boolean refresh) {
        frgRefresh2.post(new Runnable() {
            @Override
            public void run() {
                if (refresh) {
                    frgRefresh2.setRefreshing(true);
                } else {
                    frgRefresh2.setRefreshing(false);
                }
            }
        });
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (frgRefresh2.isRefreshing()) {
                        frgRefresh2.setRefreshing(false);
                    }
                    orderYesAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    };


    private void updateData() {
        OkHttpClientManager.getAsyn(url, new OkHttpClientManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                showTextToast("服务器出了点问题");
                handler.sendEmptyMessageDelayed(0, 100);
            }

            @Override
            public void onResponse(String response) {
                orderYesItemList.clear();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString("status");
                    if (status.equals("1")) {
                        JSONObject orders = jsonObject.getJSONObject("orders");
                        int count = orders.getInt("count");
                        if (count == 0) {
                            imageView.setVisibility(View.VISIBLE);
                            handler.sendEmptyMessageDelayed(0, 100);
                        } else {
                            imageView.setVisibility(View.GONE);
                            JSONArray jsonArray = orders.getJSONArray("lists");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject item = jsonArray.getJSONObject(i);
                                OrderYesItem orderYesItem = new OrderYesItem();
                                String id = item.getString("id");
                                orderYesItem.setId(id);
                                String type = item.getString("huanche");
                                //如果是0，则为送车订单
                                if (type.equals("0")) {
                                    orderYesItem.setAddress(item.getString("address"));
                                    orderYesItem.setType("送车订单");
                                    orderYesItem.setTime(item.getString("jieche_time"));
                                    orderYesItem.setPhoto(item.getJSONObject("carimg").getJSONObject("lists").getJSONObject("7").getInt("count"));
                                } else if (type.equals("1")) {
                                    orderYesItem.setAddress(item.getString("huanche_address"));
                                    orderYesItem.setType("还车订单");
                                    orderYesItem.setTime(item.getString("expect_huanchetime"));
                                    orderYesItem.setPhoto(item.getJSONObject("carimg").getJSONObject("lists").getJSONObject("8").getInt("count"));
                                }
                                String payType = item.getString("paid");
                                if (payType.equals("0")) {
                                    orderYesItem.setPayType("线下收费");
                                } else if (payType.equals("1")) {
                                    orderYesItem.setPayType("已收费");
                                }
                                orderYesItemList.add(orderYesItem);
                            }
                            handler.sendEmptyMessageDelayed(0, 100);
                            page = 2;
                        }
                    } else {
                        imageView.setVisibility(View.VISIBLE);
                        handler.sendEmptyMessageDelayed(0, 100);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    imageView.setVisibility(View.VISIBLE);
                    showTextToast("服务器出了点问题");
                }
            }
        });
    }
}
